package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Felix
 * @date 2023/7/17
 * 操作Redis的工具类
 */
public class RedisUtil {
    private static JedisPool jedisPool;
    static {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(100);
        poolConfig.setMinIdle(5);
        poolConfig.setMaxIdle(5);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setMaxWaitMillis(2000L);
        poolConfig.setTestOnBorrow(true);
        jedisPool = new JedisPool(poolConfig,"hadoop102",6379,10000);
    }
    //获取操作Redis的客户端
    public static Jedis getRedisClient(){
        System.out.println("~~~获取Jedis客户端~~~");
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }
    //关闭Redis的客户端
    public static void closeRedisClient(Jedis jedis){
        if(jedis != null){
            System.out.println("~~~关闭Jedis客户端~~~");
            jedis.close();
        }
    }

    //获取一个到redis线程安全的异步连接, key value 都用 utf-8 进行编码
    public static StatefulRedisConnection<String,String> getAsyncRedisConnection(){
        // 连接到 redis 的0号库
        System.out.println("~~~获取线程安全的异步Redis客户端~~~");
        RedisClient redisClient = RedisClient.create("redis://hadoop102:6379/0");
        return redisClient.connect();
    }
    public static void closeAsyncRedisConn(StatefulRedisConnection<String,String> redisConnection){
        if(redisConnection != null && redisConnection.isOpen()){
        System.out.println("~~~关闭线程安全的异步Redis客户端~~~");
            redisConnection.close();
        }
    }

    //异步的方式，从Redis中读取维度数据
    public static JSONObject asyncGetDimInfo(StatefulRedisConnection<String,String> redisConnection,String redisKey){
        RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();
        try {
            String dimJsonStr = asyncCommands.get(redisKey).get();
            if(dimJsonStr != null){
                return JSON.parseObject(dimJsonStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //异步的方式，向Redis中写入维度数据
    public static void asyncWriteDim(StatefulRedisConnection<String,String> redisConnection,
                                     String redisKey,
                                     JSONObject dimJsonObj){
        RedisAsyncCommands<String, String> asyncCommands = redisConnection.async();
        asyncCommands.setex(redisKey,24*3600,dimJsonObj.toJSONString());
    }

    public static void main(String[] args) {
        Jedis jedis = getRedisClient();
        String pong = jedis.ping();
        System.out.println(pong);
        closeRedisClient(jedis);
    }
}
